package com.itheima;

import org.junit.Test;

import java.util.HashMap;
import java.util.Map;

public class Topic523 {

    public boolean checkSubarraySum(int[] nums, int k) {
//        int count = 0;
        boolean result = false;

        for(int start = 0; start < nums.length; start++) {
            int sum = 0;
            for(int end = start; end >= 0; end--) {
                sum += nums[end];
                if(sum % k == 0 && start - end >= 1) {
                    result = true;
                }
            }
        }

        return result;
    }


    public boolean checkSubarraySum1(int[] nums, int k) {

        int pre = 0;
        boolean result = false;

        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, -1);
        for(int i = 0; i < nums.length; i++) {
            pre += nums[i];
            int mod = pre % k;
            if(map.containsKey(mod)) {
                int preIndex = map.get(mod);
                if(i - preIndex >= 1 && preIndex != -1) {
                    result = true;
                }
            } else {
                map.put(mod, i);
            }

        }
        System.out.println(result);
        return result;
    }


    @Test
    public void test() {

        checkSubarraySum1(new int[]{23,2,4,6,6}, 7);
    }
}
